<script setup lang="ts">
import { numberToVh } from '@/utils'
import { VxeTreeSelect } from 'vxe-pc-ui'
import { ref, reactive, nextTick, computed, onMounted, watch } from 'vue'
import { use, graphic } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { RadarChart, BarChart, PieChart } from 'echarts/charts'
import {
  TooltipComponent,
  GridComponent,
  LegendComponent,
  TitleComponent,
} from 'echarts/components'
import VChart from 'vue-echarts'
import CdcModal from '@/components/CdcModal/index.vue'
import {
  partyTeamSex,
  partyTeamXl,
  partyTeamNl,
  partyTeamDl,
  departmentalTree,
  childrenTree,
} from '@/api'
import { useUserStore } from '@/stores'
use([
  CanvasRenderer,
  RadarChart,
  BarChart,
  LegendComponent,
  PieChart,
  TooltipComponent,
  GridComponent,
  TitleComponent,
])
const userStore = useUserStore()
const cdcModalRef = ref<InstanceType<typeof CdcModal>>()
const selectValue = ref('')

const sexInfo = reactive({
  tjsj1: 0, // 女
  tjsj2: 0, // 男
})
const xlInfo = ref([
  { value: 0, name: '大专及以下', key: 'tjsj1' },
  { value: 0, name: '大学本科', key: 'tjsj2' },
  { value: 0, name: '硕士研究生', key: 'tjsj3' },
  { value: 0, name: '博士研究生', key: 'tjsj4' },
])
const nlInfo = ref([
  { value: 0, name: '25岁及以下', key: 'tjsj1' },
  { value: 0, name: '26～35岁', key: 'tjsj2' },
  { value: 0, name: '36～45岁', key: 'tjsj3' },
  { value: 0, name: '46～55岁', key: 'tjsj4' },
  { value: 0, name: '56岁及以上', key: 'tjsj5' },
])
const dlInfo = ref([
  { value: 0, name: '5年及以下', key: 'tjsj1' },
  { value: 0, name: '5～9年以下', key: 'tjsj2' },
  { value: 0, name: '10～19年以下', key: 'tjsj3' },
  { value: 0, name: '20～29年以下', key: 'tjsj4' },
  { value: 0, name: '30～39年以下', key: 'tjsj5' },
  { value: 0, name: '40年及以上', key: 'tjsj6' },
])
const colors = ['#CBFEFF', '#3ee0d5', '#3D57DF', '#83DF40', '#E4A03D', '#95D5A3']
const treeConfig = {
  lazy: true,
  async loadMethod({ node }) {
    // console.log(node)
    const data = {
      departmentId: node.departmentCode,
    }
    const res = await childrenTree(data)
    if (res.code === '200') {
      res.data.forEach((v) => {
        v.hasChild = true
      })
      return res.data
    }
  },
}
const treeData = ref<any[]>([
  { text: '第一线', departmentCode: 'ddd' },
  { text: '第二线', departmentCode: 'ddd2', hasChild: true, children: [{ text: 'a', value: 'a' }] },
])
const chartOptions = computed(() => {
  return {
    tooltip: {
      show: true,
    },
    grid: {
      top: 20,
      bottom: 30,
    },
    xAxis: {
      type: 'category',
      data: xlInfo.value.map((v) => v.name),
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: '#fff',
        padding: [10, 0, 0, 0],
      },
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#e0e0e060',
          width: 2,
          type: 'dotted',
        },
      },
    },
    series: [
      {
        type: 'bar',
        data: xlInfo.value,
        barWidth: 20,
        label: {
          show: true,
          color: '#fff',
          position: 'top',
          formatter({ value }) {
            return value + '%'
          },
        },
        zlevel: 9,
        itemStyle: {
          normal: {
            barBorderRadius: [16, 16, 0, 0],
            color: new graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: '#44FDFF',
              },
              {
                offset: 1,
                color: '#125051',
              },
            ]),
          },
        },
      },
      {
        type: 'bar',
        barWidth: 30,
        barGap: '-126%',
        data: xlInfo.value.map(() => {
          return (
            Math.max.apply(
              null,
              xlInfo.value.map((k) => k.value),
            ) || 1
          )
        }), //每一项都是总人数
        itemStyle: {
          normal: {
            color: 'rgba(55, 77, 98, 0.5)',
          },
        },
      },
    ],
  }
})
const chartOptions1 = computed(() => {
  return {
    tooltip: {
      show: true,
    },
    grid: {
      left: 0,
      top: 0,
      bottom: 0,
      containLabel: true,
    },
    xAxis: {
      show: false,
    },
    yAxis: [
      {
        type: 'category',
        inverse: true,
        data: nlInfo.value.map((v) => v.name),
        axisLabel: {
          show: true,
          textStyle: {
            color: '#fff',
            fontSize: 18,
          },
        },
        splitLine: {
          show: false, //隐藏网格线
        },
        axisTick: {
          show: false, //隐藏刻度
        },
        axisLine: {
          show: false, //隐藏坐标轴
        },
      },
      {
        type: 'category',
        inverse: true,
        show: true,
        axisTick: 'none',
        axisLine: 'none',
        axisLabel: {
          textStyle: {
            color: '#1aa3cf',
            fontSize: 18,
          },
        },
        data: nlInfo.value.map((v) => v.value + '%'), //指数组
      },
    ],
    series: [
      {
        type: 'bar',
        data: nlInfo.value.map((v) => v.value), //指柱子根据数字展示的样子
        barWidth: 20,
        label: {
          show: false,
          formatter({ value }) {
            return value + '%'
          },
        },
        showBackground: true,
        backgroundStyle: {
          borderRadius: 16,
          color: 'rgba(55, 77, 98, 0.5)',
        },
        zlevel: 9,
        itemStyle: {
          normal: {
            barBorderRadius: 16,
            color: new graphic.LinearGradient(0, 0, 1, 0, [
              {
                offset: 0,
                color: '#7dc1fd',
              },
              {
                offset: 1,
                color: '#1aa3cf',
              },
            ]),
          },
        },
      },
    ],
  }
})
const chartTextData = ref({
  subtext: dlInfo.value[0].value,
  text: dlInfo.value[0].name,
  color: colors[0],
})
const chartOptions2 = computed(() => ({
  // tooltip: {
  //   show: true,
  // },
  // grid: {
  //   right: 100,
  //   top: 0,
  //   bottom: 0,
  //   containLabel: false,
  // },
  color: colors,
  title: {
    text: chartTextData.value.text,
    left: '18%',
    top: '45%',
    itemGap: 10,
    textStyle: {
      color: '#969696',
      fontSize: 12,
    },
    subtext: `{subtext|${chartTextData.value.subtext}}{subtext_percent|%}`,
    subtextStyle: {
      rich: {
        subtext: {
          color: '#FDFDFB',
          fontSize: 28,
          fontFamily: 'DS-Digital',
          padding: [0, 6, 0, 0],
        },
        subtext_percent: {
          color: '#969696',
          fontSize: 12,
          verticalAlign: 'bottom',
        },
      },
    },
  },
  legend: {
    orient: 'vertical',
    top: numberToVh(70),
    right: 0,
    selectedMode: true, //图例的点击事件
    data: dlInfo.value.map((v) => v.name),
    align: 'left',
    itemGap: numberToVh(14),
    itemWidth: 12,
    itemHeight: 12,
    icon: 'rect',
    formatter(value: string) {
      const sum: number =
        dlInfo.value
          .map((v) => v.value)
          .reduce((pre, cur) => {
            return Number(pre) + Number(cur)
          }) || 1
      const item = dlInfo.value.find((v) => v.name === value)
      const rate = ((item.value / sum) * 100).toFixed(2)
      return `{name|${value}} {rate|${rate}}%`
    },
    textStyle: {
      color: '#cbcbcb',
      rich: {
        name: {
          color: '#cbcbcb',
          width: 150,
        },
        rate: {
          color: '#cbcbcb',
        },
      },
    },
  },
  series: [
    {
      type: 'pie',
      data: dlInfo.value,
      radius: ['62%', '70%'],
      padAngle: 2,
      colorBy: 'data',
      zlevel: 2,
      //选中某一块
      selectedMode: 'single',
      selectedOffset: 12,
      center: ['24%', '60%'],
      label: {
        show: false,
        color: '#fff',
        position: 'center',
        formatter: '{value|{c}}\n{label|{b}}',
        rich: {
          value: {
            padding: 5,
            align: 'center',
            verticalAlign: 'middle',
            fontSize: 18,
          },
          label: {
            align: 'center',
            verticalAlign: 'middle',
            fontSize: 16,
          },
        },
        emphasis: {
          //鼠标hover
          show: false,
          textStyle: {
            fontSize: '12',
          },
        },
      },
      emphasis: {
        show: false,
        scale: false,
      },
    },
    {
      type: 'pie',
      data: dlInfo.value,
      radius: ['62%', '70%'],
      center: ['24%', '60%'],
      zlevel: 1,
      label: {
        show: false,
      },
      emphasis: {
        scale: false,
      },
      itemStyle: {
        normal: {
          color: '#143530',
        },
      },
    },
    {
      type: 'pie',
      radius: ['46%', '48%'],
      center: ['24%', '60%'],
      data: dlInfo.value,
      label: {
        show: false,
      },
      zlevel: 3,
      itemStyle: {
        color: '#125051',
      },
      emphasis: {
        disabled: false,
        scale: false,
        textStyle: {
          borderColor: '#fff',
          broderRadius: 999,
          borderWidth: 2,
          padding: 4,
        },
      },
    },
  ],
}))

const handleHighLight = (e) => {
  // console.log('chart click', e)
  const { value, name, color, componentIndex, dataIndex } = e
  if (componentIndex == 0) {
    chartTextData.value.text = name
    chartTextData.value.subtext = value
    chartTextData.value.color = color
    chartRef.value?.dispatchAction({
      type: 'selected',
      seriesIndex: 0,
      dataIndex,
    })
  }
}
const chartRef = ref<InstanceType<typeof VChart> | null>(null)
watch(
  () => chartRef.value,
  (val) => {
    val?.dispatchAction({
      type: 'select',
      seriesIndex: 0,
      dataIndex: 0,
    })
  },
)
const open = () => {
  cdcModalRef.value?.showModal()
}
const selectRef = ref()
const selectIsFocus = ref(false)

const init = () => {
  const data = {
    orgId: selectValue.value,
  }
  partyTeamSex(data).then((res) => {
    if (res.code === '200') {
      Object.assign(sexInfo, res.data[0]?.statData || {})
    }
  })
  partyTeamXl(data).then((res) => {
    if (res.code === '200') {
      const r = Object.assign(xlInfo, res.data[0]?.statData || {})
      xlInfo.value.forEach((v) => {
        v.value = r[v.key] || 0
      })
    }
  })
  partyTeamNl(data).then((res) => {
    if (res.code === '200') {
      const r = Object.assign(nlInfo, res.data[0]?.statData || {})
      nlInfo.value.forEach((v) => {
        v.value = r[v.key] || 0
      })
    }
  })
  partyTeamDl(data).then((res) => {
    if (res.code === '200') {
      const r = Object.assign(dlInfo, res.data[0]?.statData || {})
      dlInfo.value.forEach((v, index) => {
        v.value = r[v.key] || 0
        if (index === 0) {
          chartTextData.value.subtext = v.value
        }
      })
    }
  })
}
const onDepChange = (item) => {
  // console.log(item)
  init()
  // console.log(selectValue)
}
onMounted(() => {
  departmentalTree({
    departmentId: userStore.userInfo.departmentId,
  }).then((res) => {
    if (res.code === '200') {
      treeData.value = res.data
      treeData.value?.forEach((v) => {
        v.hasChild = true
      })
    }
  })
  init()
})
watch(
  () => selectRef.value?.isPanelVisible(),
  (val) => {
    selectIsFocus.value = val
  },
)
defineExpose({
  open,
})
</script>

<template>
  <CdcModal
    ref="cdcModalRef"
    :data="{
      title: '党员队伍',
    }"
  >
    <div class="text-center mb-20px">
      <VxeTreeSelect
        style="vertical-align: middle"
        popup-class-name="tree-select-wrapper"
        v-model="selectValue"
        @change="onDepChange"
        :options="treeData"
        :tree-config="treeConfig"
        :option-props="{ label: 'text', value: 'departmentCode' }"
      >
      </VxeTreeSelect>
      <img
        style="vertical-align: middle"
        src="@/assets/images/arrow-down.png"
        class="vxe-icon relative right-60px arrow-down"
        :class="{
          'rotate-180': selectIsFocus,
        }"
        alt=""
      />
    </div>
    <div class="flex justify-between content">
      <div class="flex-1 mr-30px">
        <div class="flex items-center text-24px mb-16px title">
          性别
          <img src="@/assets/images/title-bg.png" class="ml-10px" height="18" alt="title_bg" />
        </div>
        <div class="content-item px-60px pb-10px female w-400px">
          <div class="flex justify-between">
            <img class="w-40px h-40px mb-14px" src="@/assets/images/male_avatar.png" alt="avatar" />

            <div class="flex flex-1 justify-between">
              <span class="flex justify-between"> 女 </span>
              <span class="text-24px text-#FDA265 leading-1 font-['DS-DIGIB-2']"
                >{{ sexInfo.tjsj1 }}%</span
              >
            </div>
          </div>
          <div class="sexLine h-14px position-relative rounded-8px">
            <p
              :style="{ width: sexInfo.tjsj1 + '%' }"
              class="female position-absolute left-0 top-0 h-100% rounded-8px"
            ></p>
          </div>
        </div>
        <div class="content-item mt-20px px-60px pb-10px male w-400px">
          <div class="flex justify-between">
            <img
              class="w-40px h-40px mb-14px"
              src="@/assets/images/female_avatar.png"
              alt="avatar"
            />
            <div class="flex justify-between flex-1">
              <span>男</span>
              <span class="text-#6BE1DD text-24px leading-1"> {{ sexInfo.tjsj2 }}% </span>
            </div>
          </div>
          <div class="sexLine h-14px position-relative male">
            <p
              :style="{ width: sexInfo.tjsj2 + '%' }"
              class="male rounded-8px position-absolute left-0 top-0 h-100%"
            ></p>
          </div>
        </div>
      </div>
      <div class="flex-1">
        <div class="flex items-center text-24px mb-16px title">
          年龄
          <img src="@/assets/images/title-bg.png" class="ml-10px" height="18" alt="title_bg" />
        </div>
        <div class="h-200px m-auto">
          <v-chart class="chart" :option="chartOptions1" autoresize />
        </div>
      </div>
    </div>
    <div class="flex justify-between mt-30px">
      <div class="flex-1 mr-30px">
        <div class="flex items-center text-24px mb-16px title">
          学历
          <img src="@/assets/images/title-bg.png" class="ml-10px" height="18" alt="title_bg" />
        </div>
        <div class="h-200px m-auto">
          <v-chart class="chart" :option="chartOptions" autoresize />
        </div>
      </div>
      <div class="flex-1">
        <div class="flex items-center text-24px mb-16px title">
          党龄
          <img src="@/assets/images/title-bg.png" class="ml-10px" height="18" alt="title_bg" />
        </div>
        <div class="h-280px m-auto relative">
          <div
            class="absolute top-0 right-0 bg-line w-280px h-50px flex justify-between items-center px-[10px] rounded-6px bg-ridial"
            :style="{
              borderBottom: `4px solid ${chartTextData.color}`,
            }"
          >
            <div class="flex items-center">
              <span
                class="mr-10px w-20px h-20px"
                :style="{
                  backgroundColor: chartTextData.color,
                }"
              ></span
              ><span>{{ chartTextData.text }}</span>
            </div>
            <span class="text-[#3EE0D5] text-[18px]">{{ chartTextData.subtext }}%</span>
          </div>

          <v-chart
            @click="handleHighLight"
            class="chart"
            :option="chartOptions2"
            autoresize
            ref="chartRef"
          />
        </div>
      </div>
    </div>
  </CdcModal>
</template>

<style lang="scss" scoped>
.content {
  .title {
    font-family: HYk2gj;
    color: transparent;
    background: linear-gradient(to bottom, #fafafc 0%, #bdf3f5 100%);
    -webkit-background-clip: text;
  }
  &-item {
    &.female {
      background-image: url('@/assets/images/femalebg.png');
    }
    &.male {
      background-image: url('@/assets/images/malebg.png');
    }
    background-position: left bottom;
    background-repeat: no-repeat;
    .sexLine {
      background-image: url('@/assets/images/linebg.png');
      background-repeat: no-repeat;
      overflow: hidden;
      width: 218px;
      height: 14px;
      .female {
        background: linear-gradient(to right, #e9b669 0%, #e56862 100%);
      }
      .male {
        background: linear-gradient(to right, #98fbfa 0%, #04a9d2 99%);
      }
    }
  }

  // .bg-line {
  //   background-image: url('../assets/images/bg_line.jpg');
  //   background-position: left bottom;
  //   background-repeat: no-repeat;
  //   background-size: 350px 44px;
  // }
}
.bg-ridial {
  background-image: radial-gradient(circle at center, #1d1d1d, #2d3e3e);
}
:deep(.vxe-tree-select) {
  width: 600px;
  height: 43px;
}
:deep(.vxe-input) {
  width: 600px;
  height: 43px;
  font-size: 20px;
  border: none;
  background-image: url('@/assets/images/select-bg.png');
  background-repeat: no-repeat;
  background-position: 100% 100%;
  background-size: cover;
  background-color: unset;
  .vxe-input--inner {
    color: #1f6fb3;
    padding-left: 40px;
    &::placeholder {
      color: #1f6fb3;
    }
  }
}
.arrow-down {
  transition: transform 0.2s ease-in-out;
}
:deep(.vxe-input--suffix-icon) {
  display: none;
}
</style>
<style>
.tree-select-wrapper {
  width: 600px;
  max-width: 600px;
}
.vxe-tree-select--panel {
  background: #15212c;
  border-radius: 4px 4px 4px 4px;
  border: 2px solid #2d5d8d;
}
.vxe-tree-select--panel-wrapper {
  background: none;
  border: none;
}
.vxe-tree.node--hover .vxe-tree--node-item:hover {
  background: none;
}
.vxe-tree--node-item-icon,
.vxe-tree--node-item-inner .vxe-tree--node-item-title {
  color: #fff;
}
.vxe-tree--node-item.is-radio--checked .vxe-tree--node-item-icon {
  color: #34a1fe;
}
.vxe-tree--node-item.is-radio--checked .vxe-tree--node-item-inner .vxe-tree--node-item-title {
  color: #34a1fe;
}
</style>
